package com.cms.interceptor;

import com.cms.common.JsonResult;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.mysql.jdbc.ExceptionInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by MOCK on 2017/8/12.
 */

public class CmsActionInterceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionInterceptor.class);

    @Override
    public void intercept(Invocation invocation) {

        try {
            Controller controller = invocation.getController();
            if (controller.getSessionAttr("admin") == null) {
                String requestURI = controller.getRequest().getRequestURI();
                if (requestURI.indexOf("/toLogin") != -1 || requestURI.indexOf("/login") != -1) {
                    invocation.invoke();
                }else {
                    String header = controller.getRequest().getHeader("X-Requested-With");
                    boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);
                    if(isAjax) {
                        controller.renderJson(new JsonResult().status("login"));
                        return;
                    }
                    controller.redirect("/toLogin");
                }
            }else {
                invocation.invoke();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            Controller controller = invocation.getController();
            HttpServletRequest request = controller.getRequest();
            //判断是否ajax请求
            String header = request.getHeader("X-Requested-With");
            boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);
            if(isAjax){
                String msg = new StringBuilder().append("{\"status\":\"-1\",\"message\":\"")
                        .append("系统繁忙，请稍后再试^_^.").append("\"}").toString();
                controller.renderJson(msg);
            }else{
                controller.renderJsp("/500.jsp");
            }
        }
    }
}
